package com.example.hello.controller;

import com.example.hello.common.Result;
import com.example.hello.dto.AdvertisementDTO;
import com.example.hello.entity.Advertisement;
import com.example.hello.service.AdvertisementService;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.example.hello.service.FileStorageService;

import jakarta.validation.Valid;

@RestController
@RequestMapping("/api/advertisement")
@Tag(name = "广告管理", description = "广告管理相关接口")
public class AdvertisementController {

    private static final Logger logger = LogManager.getLogger(AdvertisementController.class);
    
    @Autowired
    private AdvertisementService advertisementService;

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 创建广告
     */
    @PostMapping
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Operation(summary = "创建广告", description = "创建新的广告，需要管理员权限", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "创建成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足")
    })
    public Result<Advertisement> createAdvertisement(@Valid @RequestBody AdvertisementDTO advertisementDTO) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            Long userId = ((org.springframework.security.core.userdetails.User) authentication.getPrincipal()).getUsername().equals(username) ? 
                    Long.valueOf(1) : Long.valueOf(1); // 这里应该从UserDetailsService中获取用户ID
            
            Advertisement advertisement = advertisementService.createAdvertisement(advertisementDTO, userId);
            return Result.success(advertisement);
        } catch (Exception e) {
            return Result.error(500, "创建广告失败: " + e.getMessage());
        }
    }

    /**
     * 更新广告
     */
    @PutMapping("/{adId}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Operation(summary = "更新广告", description = "更新广告信息，需要管理员权限", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "404", description = "广告不存在")
    })
    public Result<Boolean> updateAdvertisement(
            @Parameter(description = "广告ID", required = true) @PathVariable Long adId,
            @Valid @RequestBody AdvertisementDTO advertisementDTO) {
        try {
            advertisementDTO.setAdId(adId);
            boolean success = advertisementService.updateAdvertisement(advertisementDTO);
            if (success) {
                return Result.success(true);
            } else {
                return Result.error(404, "广告不存在");
            }
        } catch (Exception e) {
            return Result.error(500, "更新广告失败: " + e.getMessage());
        }
    }

    /**
     * 删除广告
     */
    @DeleteMapping("/{adId}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Operation(summary = "删除广告", description = "删除广告，需要管理员权限", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "404", description = "广告不存在")
    })
    public Result<Boolean> deleteAdvertisement(
            @Parameter(description = "广告ID", required = true) @PathVariable Long adId) {
        try {
            boolean success = advertisementService.deleteAdvertisement(adId);
            if (success) {
                return Result.success(true);
            } else {
                return Result.error(404, "广告不存在");
            }
        } catch (Exception e) {
            return Result.error(500, "删除广告失败: " + e.getMessage());
        }
    }

    /**
     * 获取广告详情
     */
    @GetMapping("/{adId}")
    @Operation(summary = "获取广告详情", description = "根据ID获取广告详情")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "404", description = "广告不存在")
    })
    public Result<Advertisement> getAdvertisementById(
            @Parameter(description = "广告ID", required = true) @PathVariable Long adId) {
        try {
            Advertisement advertisement = advertisementService.getAdvertisementById(adId);
            if (advertisement != null) {
                return Result.success(advertisement);
            } else {
                return Result.error(404, "广告不存在");
            }
        } catch (Exception e) {
            return Result.error(500, "获取广告失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有广告
     */
    @GetMapping("/list")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Operation(summary = "获取所有广告", description = "分页获取所有广告，需要管理员权限", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足")
    })
    public Result<PageInfo<Advertisement>> getAllAdvertisements(
            @Parameter(description = "页码", required = false) 
            @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量", required = false) 
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            return Result.success(advertisementService.getAllAdvertisements(pageNum, pageSize));
        } catch (Exception e) {
            return Result.error(500, "获取广告列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前有效的广告
     */
    @GetMapping("/active")
    @Operation(summary = "获取当前有效的广告", description = "获取当前时间有效的广告")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功")
    })
    public Result<List<Advertisement>> getActiveAdvertisements() {
        try {
            return Result.success(advertisementService.getActiveAdvertisements());
        } catch (Exception e) {
            return Result.error(500, "获取有效广告失败: " + e.getMessage());
        }
    }

    /**
     * 获取指定位置的当前有效广告（考虑时间段）
     */
    @GetMapping("/active/position/{positionId}/timeslot")
    @Operation(summary = "获取指定位置的当前有效广告（考虑时间段）", description = "根据位置ID获取当前有效的广告，考虑每日时间段")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "404", description = "广告不存在")
    })
    public Result<List<Advertisement>> getActiveAdvertisementsByPositionAndTimeSlot(
            @Parameter(description = "广告位置ID", required = true) @PathVariable Integer positionId) {
        try {
            List<Advertisement> advertisements = advertisementService.getActiveAdvertisementsByPositionAndTimeSlot(positionId);
            return Result.success(advertisements);
        } catch (Exception e) {
            return Result.error(500, "获取广告失败: " + e.getMessage());
        }
    }

    /**
     * 发布广告
     */
    @PutMapping("/{adId}/publish")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Operation(summary = "发布广告", description = "发布广告，需要管理员权限", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "发布成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "404", description = "广告不存在")
    })
    public Result<Boolean> publishAdvertisement(
            @Parameter(description = "广告ID", required = true) @PathVariable Long adId) {
        try {
            boolean success = advertisementService.publishAdvertisement(adId);
            if (success) {
                return Result.success(true);
            } else {
                return Result.error(404, "广告不存在");
            }
        } catch (Exception e) {
            return Result.error(500, "发布广告失败: " + e.getMessage());
        }
    }

    /**
     * 下线广告
     */
    @PutMapping("/{adId}/unpublish")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Operation(summary = "下线广告", description = "下线广告，需要管理员权限", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "下线成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "404", description = "广告不存在")
    })
    public Result<Boolean> unpublishAdvertisement(
            @Parameter(description = "广告ID", required = true) @PathVariable Long adId) {
        try {
            boolean success = advertisementService.unpublishAdvertisement(adId);
            if (success) {
                return Result.success(true);
            } else {
                return Result.error(404, "广告不存在");
            }
        } catch (Exception e) {
            return Result.error(500, "下线广告失败: " + e.getMessage());
        }
    }

    /**
     * 条件查询广告列表
     */
    @GetMapping("/search")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Operation(summary = "条件查询广告列表", description = "根据条件查询广告列表，需要管理员权限", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足")
    })
    public Result<PageInfo<Advertisement>> searchAdvertisements(
            @Parameter(description = "广告标题", required = false) 
            @RequestParam(required = false) String title,
            @Parameter(description = "广告位置ID", required = false) 
            @RequestParam(required = false) Integer positionId,
            @Parameter(description = "广告状态", required = false) 
            @RequestParam(required = false) Integer status,
            @Parameter(description = "页码", required = false) 
            @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量", required = false) 
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Advertisement advertisement = new Advertisement();
            advertisement.setTitle(title);
            advertisement.setPositionId(positionId);
            advertisement.setStatus(status);
            
            return Result.success(advertisementService.getAdvertisementList(advertisement, pageNum, pageSize));
        } catch (Exception e) {
            return Result.error(500, "查询广告列表失败: " + e.getMessage());
        }
    }

    /**
     * 上传广告图片
     */
    @PostMapping("/upload/image")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Operation(summary = "上传广告图片", description = "上传广告图片，需要管理员权限", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "上传成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<List<String>> uploadAdvertisementImages(@RequestParam("files") MultipartFile[] files) {
        try {
            // 验证文件
            if (files == null || files.length == 0) {
                return Result.error(400, "请选择至少一个文件上传");
            }
            
            // 验证文件类型
            for (MultipartFile file : files) {
                String contentType = file.getContentType();
                if (contentType == null || !contentType.startsWith("image/")) {
                    return Result.error(400, "只能上传图片文件");
                }
            }
            
            // 上传文件
            List<String> urls = new ArrayList<>();
            for (MultipartFile file : files) {
                String url = fileStorageService.uploadFile(file, "advertisement/images");
                urls.add(url);
            }
            
            return Result.success(urls);
        } catch (Exception e) {
            return Result.error(500, "文件上传失败: " + e.getMessage());
        }
    }
}